<template>
  <div>
    <n-space style="margin-bottom:12px">
      <n-text>任务ID: {{ taskId }}</n-text>
      <n-button type="primary" @click="load" :loading="loading" size="small">刷新</n-button>
      <n-button type="error" ghost @click="clear" :disabled="items.length===0" size="small">清空</n-button>
    </n-space>
    
    <template v-if="items.length === 0">
      <n-empty description="暂无死信数据" />
    </template>
    <template v-else>
      <n-alert type="warning" style="margin-bottom:12px">
        共找到 {{ items.length }} 条死信消息
      </n-alert>
      <n-space vertical>
        <div v-for="(it, idx) in items" :key="idx" class="dlq-item">
          <n-card size="small" :title="`消息 #${idx + 1}`">
            <n-tabs type="line" size="small">
              <n-tab-pane name="text" tab="文本">
                <n-code :code="decode(it)" language="text" />
              </n-tab-pane>
              <n-tab-pane name="hex" tab="十六进制">
                <n-code :code="toHex(it)" language="text" />
              </n-tab-pane>
              <n-tab-pane name="base64" tab="Base64">
                <n-code :code="it" language="text" />
              </n-tab-pane>
            </n-tabs>
          </n-card>
        </div>
      </n-space>
    </template>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios'
import { ref, onMounted, watch } from 'vue'
import { NButton, NSpace, NCard, NCode, NEmpty, NText, NTabs, NTabPane, NAlert, useMessage } from 'naive-ui'

const props = defineProps<{ taskId: number | null }>()
const message = useMessage()
const items = ref<string[]>([])
const loading = ref(false)

function decode(b64: string) {
  try { 
    return atob(b64) 
  } catch { 
    return b64 
  }
}

function toHex(b64: string) {
  try {
    const binary = atob(b64)
    return Array.from(binary)
      .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))
      .join(' ')
  } catch {
    return b64
  }
}

async function load() { 
  if (props.taskId == null) return
  
  loading.value = true
  try {
    const { data } = await axios.get(`/api/dlq/${props.taskId}`)
    items.value = data
    if (data.length > 0) {
      message.success(`加载了 ${data.length} 条死信`)
    }
  } catch (e) {
    message.error('加载失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

async function clear() { 
  if (props.taskId == null) return
  
  try {
    await axios.delete(`/api/dlq/${props.taskId}`)
    await load()
    message.success('已清空') 
  } catch (e) {
    message.error('清空失败')
  }
}

watch(() => props.taskId, (newId) => {
  if (newId != null) {
    load()
  }
}, { immediate: true })
</script>
<style scoped>
.dlq-item {
  margin-bottom: 12px;
}
</style>
